const app = getApp()

const { extend, Field, Switch, Stepper, Toast, Actionsheet } = require('../../zanui/index')
import { obj2Form } from '../../utils/util.js'
import { HOST } from '../../config/apiConfig.js'

Page(extend({}, Field, Switch, Stepper, Toast, Actionsheet, {
  data: {
    submitDisabled: false,
    uploadDisabled: false,
    showMoreImgOption: false,
    moreImgOption: [{
      name: '删除该图片'
    }],
    selectImg: null,
    id: '',
    needReserveByPhone: false,
    advancedTime: 60,
    reserveStartTime: '09:00',
    reserveEndTime: '16:00',
    supplierAffirmOrderDuration: 120,
    supplierVerifyOrderDuration: 3,
    scenicImages: [],
    scenicSeasonNotice: '',
    scenicImportantExplanation: '',
    selfDrivingRoute: '',
    busRoute: '',
    discountsPolicy: '',
    freePolicy: '',
    reserveTel: '',
    supplierAffirmOrderWay: '',
    scenicConcatName1: '',
    scenicConcatPhone1: '',
    scenicConcatName2: '',
    scenicConcatPhone2: '',
    scenicVerifyWay: '',
    emergencyContactName: '',
    emergencyContactPhone: '',
    tmpImgs: []
  },
  onLoad: function (option) {
    const _self = this;
    wx.setNavigationBarTitle({
      title: '景区详细信息'
    })
    this.data.id = option.id
    wx.request({
      url: HOST + '/v1/scenic',
      data: {
        id: option.id
      },
      method: "GET",
      success: (res) => {
        const data = res.data.data[0]
        const scenicImages = []
        if (data.scenicImages != undefined) {
          _self.data.tmpImgs = data.scenicImages.split(";")
          for (let i = 0; i < _self.data.tmpImgs.length; i++) {
            scenicImages[i] = {
              src: _self.data.tmpImgs[i],
              uploadStatus: 1
            }
          }
        }
        this.setData({
          scenicSeasonNotice: data.scenicSeasonNotice,
          scenicImportantExplanation: data.scenicImportantExplanation,
          selfDrivingRoute: data.selfDrivingRoute,
          busRoute: data.busRoute,
          discountsPolicy: data.discountsPolicy,
          freePolicy: data.freePolicy,
          needReserveByPhone: data.needReserveByPhone == 0 ? false : true,
          reserveTel: data.reserveTel,
          advancedTime: data.advancedTime,
          reserveStartTime: data.reserveStartTime,
          reserveEndTime: data.reserveEndTime,
          supplierAffirmOrderWay: data.supplierAffirmOrderWay,
          supplierAffirmOrderDuration: data.supplierAffirmOrderDuration,
          supplierVerifyOrderDuration: data.supplierVerifyOrderDuration,
          scenicConcatName1: data.scenicConcatName1,
          scenicConcatPhone1: data.scenicConcatPhone1,
          scenicConcatName2: data.scenicConcatName2,
          scenicConcatPhone2: data.scenicConcatPhone2,
          scenicVerifyWay: data.scenicVerifyWay,
          emergencyContactName: data.emergencyContactName,
          emergencyContactPhone: data.emergencyContactPhone,
          noTicketEmergencyDisposeWay: data.noTicketEmergencyDisposeWay,
          scenicImages: scenicImages
        })
      }
    })
  },
  bindPickerChange(e) {
    this.setData({
      [`${e.currentTarget.id}`]: e.detail.value
    })
  },
  handleZanStepperChange({ componentId, stepper }) {
    this.setData({
      [`${componentId}`]: stepper
    });
  },
  handleZanSwitchChange({ componentId, checked }) {
    this.setData({
      [`${componentId}`]: checked
    });
  },
  selectImgs(e) {
    const _self = this
    wx.chooseImage({
      count: 12,
      sizeType: ['original'],
      sourceType: ['album'],
      success: function (res) {
        let tmp = _self.data.scenicImages
        res.tempFilePaths.forEach((path, index) => {
          tmp.push({
            id: new Date().getTime() + '-' + index,
            src: path,
            uploadStatus: 0
          })
        })
        if (tmp.length > 12) {
          tmp = tmp.slice(0, 12)
        }
        _self.setData({
          scenicImages: tmp
        })
      }
    })
  },
  uploadImg() {
    this.setData({
      uploadDisabled: true
    })
    wx.showLoading({
      title: '上传图片中',
    })

    //函数数组，每个函数的返回值是一个promise对象
    let promiseFuncArr = []
    const _self = this
    this.data.scenicImages.forEach(item => {
      if (item.uploadStatus != 1) {
        let promiseTemp = function () {
          return new Promise((resolve, reject) => {
            wx.uploadFile({
              url: 'https://qdndcupload.ideatower.cn/apiAttachment/uploadAttachment?bucketName=qdndc',
              filePath: item.src,
              name: 'file',
              success: function (res) {
                var data = JSON.parse(res.data)
                if (data.code == 0) {
                  item.downloadPath = data.data[0].downloadPath
                }
                resolve(item)
              },
              fail: function () {
                reject(error)
              },
              complete: function () {
              }
            })
          })
        }
        promiseFuncArr.push(promiseTemp)
      }
    })
    _self.sequenceTasks(promiseFuncArr).then((result) => {
      //对返回的result数组进行处理
      if (promiseFuncArr.length == 0) {
        wx.hideLoading()
        this.showZanToast('请至少选择一张新的图片')
        return
      }
      result.forEach(item => {
        if (item.downloadPath) {
          item.uploadStatus = 1
        } else {
          item.uploadStatus = -1
        }
      })
      _self.data.scenicImages.forEach(item => {
        const findObj = result.find(o => o.id == item.id)
        if (findObj) {
          item = Object.assign({}, item, findObj)
        }
      })
      _self.setData({
        scenicImages: _self.data.scenicImages,
        uploadDisabled: false
      })

      wx.hideLoading()
    })
  },
  bindImgLongTab(e) {
    let index = e.currentTarget.id.substring(3)
    const img = this.data.scenicImages[parseInt(index)]
    if (img.uploadStatus == -1) {
      this.setData({
        moreImgOption: [{
          name: '删除该图片'
        }, {
          name: '重新上传'
        }]
      })
    } else {
      this.setData({
        moreImgOption: [{
          name: '删除该图片'
        }]
      })
    }

    this.setData({
      selectImg: img,
      showMoreImgOption: true
    })
  },
  handleZanActionsheetCancel() {
    this.setData({
      showMoreImgOption: false
    })
  },
  handleZanActionsheetClick({ componentId, index }) {
    if (this.data.selectImg) {
      const t1 = this.data.scenicImages
      if (index == 0) {
        // 删除
        const findIndex1 = t1.findIndex(o => o.id == this.data.selectImg.id)
        if (findIndex1 > -1) {
          t1.splice(findIndex1, 1)
          this.setData({
            scenicImages: t1
          })
        }
      } else {
        // 重新上传
        wx.showLoading({
          title: '上传图片中',
        })
        const obj = t1.find(o => o.id == this.data.selectImg.id)
        if (obj) {
          const _self = this
          wx.uploadFile({
            url: 'https://qdndcupload.ideatower.cn/apiAttachment/uploadAttachment?bucketName=qdndc',
            filePath: obj.src,
            name: 'file',
            success: function (res) {
              var data = JSON.parse(res.data)
              if (data.code == 0) {
                obj.downloadPath = data.data[0].downloadPath
              }
            },
            fail: function () {
            },
            complete: function () {
              t1.forEach(item => {
                if (item.id == obj.id) {
                  if (obj.downloadPath) {
                    item.uploadStatus = 1
                    item.downloadPath = obj.downloadPath
                  } else {
                    item.uploadStatus = -1
                  }
                }
              })
              _self.setData({
                scenicImages: t1,
              })
              wx.hideLoading()
            }
          })
        }
      }
      this.setData({
        showMoreImgOption: false
      })
    }
  },
  formSubmit(event) {
    const tmpImgs = []
    this.data.scenicImages.forEach(item => tmpImgs.push(item.downloadPath))
    const data = event.detail.value
    for (let key in data) {
      if (key == 'needReserveByPhone' && this.data.needReserveByPhone == true && data.reserveTel == '') {
        this.showZanToast('请填写电话预约的手机号')
        return
      }
      if (data[key] == '' && key != 'scenicSeasonNotice' && key != 'scenicImportantExplanation'
        && key != 'scenicContactName2' && key != 'scenicContactPhone2') {
        this.showZanToast('必填字段不能为空')
        return
      }
    }
    if (tmpImgs.length < 5) {
      this.showZanToast('景区图片不能少于5张')
      return
    }
    if (tmpImgs.length > 12) {
      this.showZanToast('景区图片不能超过12张')
      return
    }
    this.setData({
      submitDisabled: true
    })
    data.needReserveByPhone = this.data.needReserveByPhone ? 1 : 0
    console.log("this.data.scenicImages.length:" + this.data.scenicImages.length)
    if (this.data.tmpImgs.length == 0) {
      data.scenicImages = tmpImgs.join(';')
    } else {
      data.scenicImages = this.data.tmpImgs.join(';')
    }
    console.log(data.scenicImages)
    data.updateBy = app.globalData.userInfo.openid
    data.advancedTime = 60
    data.supplierAffirmOrderDuration =120
    data.supplierVerifyOrderDuration = 3
    if (this.data.advancedTime != undefined){
      data.advancedTime = this.data.advancedTime
    }
    if (this.data.supplierAffirmOrderDuration != undefined){
      data.supplierAffirmOrderDuration = this.data.supplierAffirmOrderDuration
    }
    if (this.data.supplierVerifyOrderDuration != undefined){
      data.supplierVerifyOrderDuration = this.data.supplierVerifyOrderDuration
    }
    wx.showLoading({
      title: '提交数据中...',
    })
    const _self = this
    wx.request({
      url: 'https://qdndc.ideatower.cn/v1/scenic/' + this.data.id,
      header: {
        "Content-Type": "application/x-www-form-urlencoded"
      },
      data: obj2Form(data),
      method: 'PUT',
      success: function (res) {
        if (res.statusCode != 200) {
          _self.showZanToast('请求接口失败')
          return
        }
        if (res.data.code != '000000') {
          _self.showZanToast(res.data.message)
          return
        }
        _self.showZanToast('提交成功')
        setTimeout(() => {
          wx.navigateBack({
            delta: 2
          })
        }, 300)
      },
      fail: function () {
        _self.showZanToast('网络错误')
      },
      complete: function () {
        _self.setData({
          submitDisabled: false
        })
        wx.hideLoading()
      }
    })
  },
  //顺序处理函数
  sequenceTasks(tasks) {
    //记录返回值
    function recordValue(results, value) {
      results.push(value)
      return results
    }
    let pushValue = recordValue.bind(null, [])
    return tasks.reduce(function (promise, task) {
      return promise.then(task).then(pushValue)
    }, Promise.resolve())
  }
}))
